//
//  LightSensitive.m
//  测试demo
//
//  Created by ycx on 2019/7/2.
//  Copyright © 2019 ycx. All rights reserved.
//

#import "LightSensitive.h"
@import AVFoundation;

#import <ImageIO/ImageIO.h>

@interface LightSensitive()<
AVCaptureVideoDataOutputSampleBufferDelegate>

@property (nonatomic, strong) AVCaptureSession *session;

@end


@implementation LightSensitive
-(instancetype)init
{
    if(self == [super init])
    {
       // [self initialization];
    }
    return self;
}
-(void)initialization
{
    // 1.获取硬件设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 2.创建输入流
    AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc]initWithDevice:device error:nil];
    
    // 3.创建设备输出流
    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
    [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
    
    
    // AVCaptureSession属性
    self.session = [[AVCaptureSession alloc]init];
    // 设置为高质量采集率
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    // 添加会话输入和输出
    if ([self.session canAddInput:input]) {
        [self.session addInput:input];
    }
    if ([self.session canAddOutput:output]) {
        [self.session addOutput:output];
    }
    
    // 9.启动会话
    [self.session startRunning];
    
}
#pragma mark- AVCaptureVideoDataOutputSampleBufferDelegate的方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    
    CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
    NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
    CFRelease(metadataDict);
    NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
    float brightnessValue = [[exifMetadata objectForKey:(NSString *)kCGImagePropertyExifBrightnessValue] floatValue];
    
    NSLog(@"%f",brightnessValue);
    
    if(self.block)
    {
        self.block(brightnessValue);
    }
        
//    // 根据brightnessValue的值来打开和关闭闪光灯
//    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//    BOOL result = [device hasTorch];// 判断设备是否有闪光灯
//    if ((brightnessValue < 0) && result) {// 打开闪光灯
//
//        [device lockForConfiguration:nil];
//
//        [device setTorchMode: AVCaptureTorchModeOn];//开
//
//        [device unlockForConfiguration];
//
//    }else if((brightnessValue > 0) && result) {// 关闭闪光灯
//
//        [device lockForConfiguration:nil];
//        [device setTorchMode: AVCaptureTorchModeOff];//关
//        [device unlockForConfiguration];
//
//    }
    
}

@end
